package com.example.springboot.endpoint.server;

import com.example.springboot.endpoint.config.WebSocketConfig;
import org.springframework.stereotype.Component;

import javax.websocket.CloseReason;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.time.LocalDateTime;

/**
 * <p> 路径上带参数的
 *
 * @author Zhang.Z
 * @version 2025-09-21
 * @see WebSocketConfig
 */
@Component
@ServerEndpoint(value = "/ws/{userId}")
public class WebSocketPathServerEndpoint {


    /**
     * 当客户端与服务端建立 WebSocket 连接时触发。
     * <p> 可以在这里保存 Session，初始化资源
     */
    @OnOpen
    public void onOpen(@PathParam("userId") String userId, Session session) throws Exception {
        System.out.println("连接的用户ID: " + userId);
    }


    /**
     * 接收到文本消息时触发
     */
    @OnMessage
    public void onTextMessage(@PathParam("userId") String userId, String message, Session session) throws Exception {
        System.out.println(userId + " : " + message);
        //发送数据
        session.getBasicRemote().sendText(LocalDateTime.now().toString());
    }


    /**
     * 当连接关闭时触发。可以做清理工作，例如移除 session。
     */
    @OnClose
    public void onClose(@PathParam("userId") String userId,Session session, CloseReason reason) throws IOException {

        System.out.printf("userId = {%s} 关闭链接, 关闭消息 = { %s } %n", userId, reason.getReasonPhrase());

        if (session.isOpen()) {
            session.close();
        }
    }


    /**
     * 当发生错误（如 IO 异常、编码异常）时触发
     */
    @OnError
    public void OnError(Session session, Throwable throwable) {
        System.out.printf("【%s】 链接异常, %s%n", session.getId(), throwable.getMessage());
    }
}
